package com.jeeplus.modules.work.queue.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.modules.sys.utils.FileKit;
import com.jeeplus.modules.work.queue.service.RealEstateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;

import static com.jeeplus.modules.work.queue.utils.HttpUtilsBDC.SendPost;

@RestController
@Api(tags = "不动产")
@RequiredArgsConstructor
@RequestMapping(value = "/RealEstate")
public class RealEstateController {
    /**
     * 业务ＩＤ
     */
    @Value("${SerialId}")
    private String SerialId;

    /**
     * 不动产在大厅所在区域的区域编号
     */
    @Value("${Sysno}")
    private String Sysno;
    /**
     * 不动产登录账号
     */
    @Value("${realEstateLoginName}")
    private String realEstateLoginName;
    /**
     * 不动产登录密码
     */
    @Value("${realEstatePassWord}")
    private String realEstatePassWord;
    /**
     * 不动产机构标识
     */
    @Value("${realEstateIdentification}")
    private String realEstateIdentification;
    /**
     * 不动产密钥
     */
    @Value("${realEstateSecretKey}")
    private String realEstateSecretKey;

    /**
     * 不动产系统排号信息上传参考号使用前需要先在前面拼接日期（格式：20220111）
     */
    @Value("${realEstateInfoRefId}")
    private String realEstateInfoRefId;

    /**
     * 不动产系统Token参考号使用前需要先在前面拼接日期（格式：20220111）
     */
    @Value("${realEstateTokenRefId}")
    private String realEstateTokenRefId;


    /**
     * 不动产Token报文编号
     */
    @Value("${realEstateTokenTrnCode}")
    private String realEstateTokenTrnCode;
    /**
     * 不动产获取办件信息报文编号
     */
    @Value("${realEstateDoThingInfoTrnCode}")
    private String realEstateDoThingInfoTrnCode;
    /**
     * 不动产推送排号信息报文标识
     */
    @Value("${realEstateInfoTrnCode}")
    private String realEstateInfoTrnCode;

    private final RealEstateService service;
    @PostMapping("getQuantity")
    @ApiOperation(value = "不动产")
    public AjaxJson getQuantity(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String format = df.format(new Date());
        Map<String,String> map=new HashMap<>();
        map.put("serialId",SerialId);
        map.put("sysno",Sysno);
        map.put("startTime",format);
        Map<String, Map<String, Integer>> quantity = service.getQuantity(map);
        //获取token
        String token=getToken();
        long l = System.currentTimeMillis() / 1000;
         df = new SimpleDateFormat("yyyyMMdd");
         format = df.format(new Date());
        String StringA="{"+
                "\"MsgHeader\":{"+
                "\"TrnCode\":\""+realEstateInfoTrnCode+"\","+
                "\"RefId\":\""+format+realEstateInfoRefId+"\","+
                "\"ReqRefId\":\"\","+
                "\"Token\":\""+token+"\","+
                "\"Remark\":\"\""+
                "},"+
                "\"MsgBody\":{"+
                "\"QHDM\":\"510101\","+
                "\"BLD\":\"1\","+
                "\"QD\":\"1\","+
                "\"FHSJ\":["+
                "{"+
                "\"FHLX\":\"0\","+
                "\"FHSL\":"+quantity.get("Total").get("totalGetNum")+","+
                "\"YJHSL\":"+quantity.get("Total").get("totalCallNum")+
                "},"+
                "{"+
                "\"FHLX\":\"1\","+
                "\"FHSL\":"+quantity.get("OneWindow").get("oneWindowGetNum")+","+
                "\"YJHSL\":"+quantity.get("OneWindow").get("oneWindowCallNum")+
                "}"+
                "]"+
                "}"+
                "}";
        JSONObject jsonObject = JSONObject.fromObject(StringA);
        String sign="Content="+jsonObject.toString()+"&Key="+realEstateSecretKey+"&Timestamp="+l;
        System.out.println(sign);
        sign = DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase();
        String parameter="{"+
                "\"Content\":\"{"+
                "\\\"MsgHeader\\\":{"+
                "\\\"TrnCode\\\":\\\""+realEstateInfoTrnCode+"\\\","+
                "\\\"RefId\\\":\\\""+format+realEstateInfoRefId+"\\\","+
                "\\\"ReqRefId\\\":\\\"\\\","+
                "\\\"Token\\\":\\\""+token+"\\\","+
                "\\\"Remark\\\":\\\"\\\""+
                "},"+
                "\\\"MsgBody\\\":{"+
                "\\\"QHDM\\\":\\\"510101\\\","+
                "\\\"BLD\\\":\\\"1\\\","+
                "\\\"QD\\\":\\\"1\\\","+
                "\\\"FHSJ\\\":["+
                "{"+
                "\\\"FHLX\\\":\\\"0\\\","+
                "\\\"FHSL\\\":"+quantity.get("Total").get("totalGetNum")+","+
                "\\\"YJHSL\\\":"+quantity.get("Total").get("totalCallNum")+
                "},"+
                "{"+
                "\\\"FHLX\\\":\\\"1\\\","+
                "\\\"FHSL\\\":"+quantity.get("OneWindow").get("oneWindowGetNum")+","+
                "\\\"YJHSL\\\":"+quantity.get("OneWindow").get("oneWindowCallNum")+
                "}"+
                "]"+
                "}"+
                "}\","+
                "\"OrgId\":\""+realEstateIdentification+"\","+
                "\"Sign\":\""+sign+"\","+
                "\"Timestamp\":\""+l+"\""+
                "}";
        String s = SendPost(parameter);
        System.out.println(s);
        return AjaxJson.success();
    }

    /**
     * 获取Token
     * @return Token
     */
    public String getToken(){
        long l = System.currentTimeMillis() / 1000;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String format = df.format(new Date());
        String StringA="{"+
                "\"MsgHeader\":{"+
                "\"TrnCode\":\""+realEstateTokenTrnCode+"\","+
                "\"RefId\":\""+format+realEstateTokenRefId+"\","+
                "\"ReqRefId\":\"\","+
                "\"Token\":\"\","+
                "\"Remark\":\"\""+
                "},"+
                "\"MsgBody\":{"+
                "\"LoginName\":\""+realEstateLoginName+"\","+
                "\"PassWord\":\""+realEstatePassWord+"\""+
                "}}";
        String sign="Content="+StringA+"&Key="+realEstateSecretKey+"&Timestamp="+l;
        sign = DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase();
        String parameter="{"+
                "\"Content\":\"{"+
                "\\\"MsgHeader\\\":{"+
                "\\\"TrnCode\\\":\\\""+realEstateTokenTrnCode+"\\\","+
                "\\\"RefId\\\":\\\""+format+realEstateTokenRefId+"\\\","+
                "\\\"ReqRefId\\\":\\\"\\\","+
                "\\\"Token\\\":\\\"\\\","+
                "\\\"Remark\\\":\\\"\\\""+
                "},"+
                "\\\"MsgBody\\\":{"+
                "\\\"LoginName\\\":\\\""+realEstateLoginName+"\\\","+
                "\\\"PassWord\\\":\\\""+realEstatePassWord+"\\\""+
                "}"+
                "}\","+
                "\"OrgId\":\""+realEstateIdentification+"\","+
                "\"Sign\":\""+sign+"\","+
                "\"Timestamp\":\""+l+"\""+
                "}";
        String s = SendPost(parameter);
        s = JSONObject.fromObject(s).getString("Content");
        s = JSONObject.fromObject(s).getJSONObject("MsgBody").getString("Token");
        return s;
    }


    @GetMapping("getThatDay")
    public AjaxJson getThatDay(String time){
        String fileName = "办件统计"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
        //创建excle
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle cellStyle = wb.createCellStyle();//设置样式
        cellStyle.setBorderBottom(BorderStyle.THIN);//设置下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//设置左边框
        cellStyle.setBorderRight(BorderStyle.THIN);//设置右边框
        cellStyle.setBorderTop(BorderStyle.THIN);//设置上边框
        cellStyle.setBottomBorderColor((short)1);//设置边框颜色
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//居中
        //通过HSSFWorkbook创建一个HSSFFont
        HSSFFont font = wb.createFont();
        //设置一个字体的颜色2表示红色3表示绿色4表示蓝色5表示黄色6表示紫色7表示亮蓝色8表示黑色9表示白色
        font.setColor((short)8);
        //设置字体的风格：仿宋_GB2312、黑体
        font.setFontName("黑体");
        //设置一个字体的大小,此数值的取值与Excel中的字体大小取值一样
        font.setFontHeightInPoints((short) 12);
        cellStyle.setWrapText(true);//设置自动换行
        //设置背景色
        cellStyle.setFillForegroundColor((short) 13);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //把该字体应用到当前的样式
        font.setBold(true);
        cellStyle.setFont(font);
        String[] data = {"区域", "数量"};
        HSSFSheet sheet = wb.createSheet("办件统计");
        //设置列宽，其中width表示Excel中的列宽值
        //firstRow：起始行 lastRow：结束行 firstCol：起始列 lastCol：结束列
        //CellRangeAddress region = new CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol);
        //sheet.addMergedRegion(region);
        try {
            HSSFRow row = null;
            HSSFCell hc = null;
            row = sheet.createRow(0);
            for(int i =0;i<data.length;i++){
                hc = row.createCell(i);
                hc.setCellStyle(cellStyle);
                hc.setCellValue(data[i]);
                sheet.setColumnWidth(i, 4000); //第一个参数代表列id(从0开始),第2个参数代表宽度值
            }
            List<Map<String, Object>> quanQu = service.getQuanQu(time);
            Collections.sort(quanQu, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if(!o1.get("area").equals(o2.get("o2"))){
                        return (o1.get("area")+"").compareTo(o2.get("area")+"");
                    }else {
                        return (int)o1.get("number")-(int)o2.get("number");
                    }

                }
            });
            int num = 1;
            ExecutorService pool = null;
            //加载第一次数据集合进入excle
            for(int key=0;key<quanQu.size();key++){
                row = sheet.createRow(num);
                row.createCell(0).setCellValue(quanQu.get(key).get("area")+"");
                row.createCell(1).setCellValue(quanQu.get(key).get("number")+"");
                num++;
            }

            //文档输出
            String fileDir = FileKit.getUserAttachmentDir("gxzw")+"excle/queue/";
            FileUtils.createDirectory(fileDir);
            fileDir = fileDir+fileName;
            FileOutputStream out = new FileOutputStream(fileDir);
            wb.write(out);
            out.flush();
            out.close();
            //关闭多线程
            if(null != pool){
                pool.shutdown();
            }
            return AjaxJson.success().put("url","C:/soft/web/systemImg/"+fileDir.substring(fileDir.indexOf("userfiles"),fileDir.length()));
        }catch (Exception e){}
        return AjaxJson.error("导出失败！");
    }

}
